package com.ezcolour.ticket.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ezcolour.ticket.web.global.GlobalCache;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class CrawlerUtil {


    /**
     *  获取companyId
     *
     */
    public static String getCompanyId(String vocalId){
        String result =null;
        try{
            Connection companyConn = Jsoup
                    .connect("https://piao.damai.cn/"+vocalId+".html");// 获取连接
            companyConn.header("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览器
            Connection.Response companyRs = companyConn.ignoreContentType(true).method(Connection.Method.GET)
                    .execute();
            Document d1 = Jsoup.parse(companyRs.body());// 转换为Dom树
            Elements inputForCompanyId = d1.select("#cityId");
            result = inputForCompanyId.val();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     *  获取列表
     *
     */
    public static String getProjectList(String keyword){
        String result =null;
        try{
            Map<String, String> searchDatas = new HashMap<>();
            searchDatas.put("keyword",keyword);
            searchDatas.put("cty","");
            searchDatas.put("ctl","演唱会");
            searchDatas.put("order","1");
            searchDatas.put("tn","");
            searchDatas.put("sctl","");
            Connection listConn = Jsoup
                    .connect("https://search.damai.cn/searchajax.html");// 获取连接
            listConn.header("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览器
            Connection.Response listRs = listConn.ignoreContentType(true).method(Connection.Method.POST)
                    .data(searchDatas).execute();
            result = listRs.body();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     *  获取商品详情
     *
     */
    public static String getInfo(String vocalId){
        String result =null;
        try{
            Connection proConn = Jsoup
                    .connect("https://piao.damai.cn/ajax/getInfo.html?projectId="+vocalId);// 获取连接
            proConn.header("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览器
            Connection.Response proRs = proConn.ignoreContentType(true).method(Connection.Method.GET)
                    .execute();
            /*JSONObject jsonObject = JSONObject.parseObject(proRs.body());
            JSONObject data = (JSONObject) jsonObject.get("Data");
            JSONArray performs = (JSONArray)data.get("performs");
            JSONArray prices = (JSONArray)data.get("prices");*/
            //如果statu等于0 则有货
            result = proRs.body();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     *  获取商品价格列表
     *
     */
    public static String getPriceList(String vocalId, String performId){
        String result =null;
        //生成时间戳 随机串
        Long time = new Date().getTime();
        String str = ""+time + (new Random().nextInt(8999) + 1000);
        try{
            Connection proConn = Jsoup
                    .connect("https://piao.damai.cn/ajax/getPriceList.html?projectId="+vocalId+"&performId="+performId+"&t="+str);// 获取连接
            proConn.header("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览器
            Connection.Response proRs = proConn.ignoreContentType(true).method(Connection.Method.GET)
                    .execute();
            result = proRs.body();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    /**
     *  获取商品状态
     *
     */
    public static Boolean getStatu(String vocalId, String performId, String priceId){
        Boolean result =false;
        try{
            //生成时间戳 随机串
            Long time = new Date().getTime();
            String str = ""+time + (new Random().nextInt(8999) + 1000);
            //performId存在直接查询
            JSONArray prices = null;
            JSONObject price = null;
            if(performId != null){
                Connection listConn = Jsoup
                        .connect("https://piao.damai.cn/ajax/getPriceList.html?projectId="+vocalId+"&performId="+performId+"&t="+str);// 获取连接
                listConn.header("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览器
                Connection.Response listRs = listConn.ignoreContentType(true).method(Connection.Method.GET)
                        .execute();
                JSONObject jsonObject = JSONObject.parseObject(listRs.body());
                JSONObject data = (JSONObject) jsonObject.get("Data");
                prices = (JSONArray)data.get("list");

            }else{
                //performId不存在查询默认页
                Connection proConn = Jsoup
                        .connect("https://piao.damai.cn/ajax/getInfo.html?projectId="+vocalId);// 获取连接
                proConn.header("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览器
                Connection.Response proRs = proConn.ignoreContentType(true).method(Connection.Method.GET)
                        .execute();
                JSONObject jsonObject = JSONObject.parseObject(proRs.body());
                JSONObject data = (JSONObject) jsonObject.get("Data");
                prices = (JSONArray)data.get("prices");
            }
            if(prices == null){
                System.out.println("没有相应价格场次");
                return result;
            }
            for (Object good:
                    prices) {
                price =(JSONObject)good;
                System.out.println("传入id:"+priceId);
                System.out.println("获取id:"+price.get("PriceID"));
                System.out.println(price.toString());
                String pid= price.get("PriceID").toString();
                if(pid.equals(priceId)){
                    Integer statu = (Integer)price.get("Status");
                    System.out.println(statu);
                    //如果statu等于0 则有货
                    switch (statu){
                        case 0 :
                            result = true;
                            break;
                        default:
                            result = false;
                            break;
                    }
                    if(result){
                        break;
                    }
                }
            }

        }catch (Exception e){
            System.out.println("发生异常："+e.getMessage());
        }
        return result;
    }

    /**
     *  web端发送订单
     *  @param vocalId  演唱会id
     *  @param cookies  cookies
     *  @param proId    价格id
     *  @param companyId    城市id
     *  @param number   数量
     */
    public static String goShop(String vocalId,Map<String, String> cookies,String proId,String companyId,String number){
        String result =null;
        Map<String, String> orderDatas = new HashMap<>();
        orderDatas.put("_action","Immediately");
        orderDatas.put("proId",proId);//价格id
        orderDatas.put("optype","1");
        orderDatas.put("companyId",companyId);//城市id
        orderDatas.put("num",number);//城市id
        orderDatas.put("n","0");//城市id
        try{
            Connection shopConn = Jsoup
                    .connect("https://www.damai.cn/GotoShopping.aspx");// 获取连接
            shopConn.header("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览器
            Connection.Response proRs = shopConn.ignoreContentType(true).method(Connection.Method.GET)
                    .data(orderDatas).cookies(cookies).execute();
            /*JSONObject jsonObject = JSONObject.parseObject(proRs.body());
            JSONObject data = (JSONObject) jsonObject.get("Data");
            JSONArray performs = (JSONArray)data.get("performs");
            JSONArray prices = (JSONArray)data.get("prices");*/
            result = proRs.body();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


    /**
     *  查询购票人信息
     *  @param vocalId  演唱会id
     *  @param cookies  cookies
     *  @param proId    价格id
     *  @param companyId    城市id
     *  @param number   数量
     */
    public static String getUserInfo(String vocalId,Map<String, String> cookies,String proId,String companyId,String number){
        String result =null;
        String res= goShop(vocalId, cookies, proId, companyId, number).replaceAll("'","").replaceAll("\\\\","");
        int index = res.indexOf("t_queryCommodityVo");
        String substring = res.substring(index);
        String substring1 = substring.substring(substring.indexOf("{"), substring.indexOf("}")+1);
        JSONObject jsonObject = JSONObject.parseObject(substring1);
//        String idTypes = (String)jsonObject.get("idTypes");
        Map<String, String> query = new HashMap<>();
        query.put("sellChannel",jsonObject.get("sellChannel").toString());
        query.put("businessType",jsonObject.get("businessType").toString());
        query.put("businessSubType",jsonObject.get("businessSubType").toString());
        query.put("commodity",jsonObject.get("commodity").toString());
        query.put("cityId",jsonObject.get("cityId").toString());
        query.put("oid",jsonObject.get("oid").toString());
        query.put("tid",jsonObject.get("tid").toString());
        query.put("idTypes","1");
        try{
            Connection buyConn = Jsoup
                    .connect("https://buy.damai.cn/multi/ajaxhandler/querySecurityIdInfo");// 获取连接
            buyConn.header("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览器
            Connection.Response buyRs = buyConn.ignoreContentType(true).method(Connection.Method.POST)
                    .data(query).cookies(cookies).execute();
            System.out.println(buyRs.body());
            result = buyRs.body();
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
    //https://buy.damai.cn/multi/trans/submitOrderInfo
    /**
     *  web端发送订单
     *  @param vocalId  演唱会id
     *  @param cookies  cookies
     *  @param priceId    价格id
     *  @param companyId    城市id
     *  @param number   数量
     */
    /*public static String goPhoneBuy(String vocalId,Map<String, String> cookies,String priceId,String performId,String companyId,String number){
        String result =null;
        Map<String, String> orderDatas = new HashMap<>();
        orderDatas.put("commodity","2|"+priceId+"^"+number+"^"+performId);
        orderDatas.put("cityId",companyId);//价格id
        orderDatas.put("projectId",vocalId);
        orderDatas.put("privilegeId","0");//城市id
        orderDatas.put("spm","a2o71.selectitem.bottom.dselectsubmit");//城市id
        try{
            Connection shopConn = Jsoup
                    .connect("http://m.damai.cn/damai/trade/index.html");// 获取连接
            shopConn.header("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");// 配置模拟浏览器
            Connection.Response proRs = shopConn.ignoreContentType(true).method(Connection.Method.GET)
                    .data(orderDatas).cookies(cookies).execute();
            result = proRs.body();

            ConcurrentHashMap<Long, String> longStringConcurrentHashMap = new ConcurrentHashMap<Long, String>();
            longStringConcurrentHashMap.put(1L,result);
            GlobalCache.user_vocal_html.put(1L,longStringConcurrentHashMap);
            ConcurrentHashMap<Long, Map<String, String>> cookieHashMap = new ConcurrentHashMap<Long, Map<String, String>>();
            cookieHashMap.put(1L,proRs.cookies());
            GlobalCache.user_vocal_cookies.put(1L,cookieHashMap);
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }*/
}
